package system.config;

import framework.config.FileConfig;
import framework.config.FileManagerConfig;
import framework.config.FileStorageHttpConfig;
import framework.config.S3Config;
import framework.exceptions.ConfigurationException;
import framework.storage.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 存储系统配置
 */
@Configuration
@Slf4j
public class FileStorageConfig {

    @Bean
    @ConditionalOnProperty(name = "file.manager.enable", havingValue = "true")
    public FileManager fileManager(FileManagerConfig fileManagerConfig) throws ConfigurationException {
        FileManagerDefault manager = new FileManagerDefault(fileManagerConfig);
        log.info("Enable fileManager: {}", manager.getClass().getSimpleName());
        return manager;
    }

    @Bean
    public FileStorage fileStorage(FileConfig fileConfig, S3Config s3Config, FileStorageHttpConfig fileStorageHttpConfig
            , @Autowired(required = false) FileManager fileManager) throws ConfigurationException {
        FileStorage fileStorage = null;

        //
        if ("local".equals(fileConfig.getStorageType())) {
            fileStorage = new FileStorageLocal(fileConfig);
        } else if ("s3".equals(fileConfig.getStorageType())) {
            fileStorage = new FileStorageS3(s3Config);
        } else if ("http".equals(fileConfig.getStorageType())) {
            fileStorage = new FileStorageHttp(fileStorageHttpConfig);
        } else if ("manager".equals(fileConfig.getStorageType())) {
            if (fileManager == null) {
                throw new ConfigurationException("storage failed: file.storage-type config manager, but not enable file manager");
            }
            fileStorage = fileManager;
        } else if ("none".equals(fileConfig.getStorageType())) {
            fileStorage = new FileStorageNone();
        } else {
            throw new ConfigurationException("storage driver: not configured");
        }

        //
        log.info("Enable fileStorage: {}", fileStorage.getClass().getSimpleName());
        return fileStorage;
    }

}
